<?php
namespace Modules\Auth\API;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Modules\Common\Exceptions\BaseException;
use Modules\Common\Exceptions\ServerException;


class APIHelper
{
    private $client;
    private $passportTokenUrl;
    public function __construct() {
        $this->client = new Client();
        $this->passportTokenUrl = config('app.url') . "/" . config("auth.passport.prefix", 'oauth') . '/token';
    }
    /**
     * 获取对应配置
     *
     * @param string $name
     *
     * @return array
     * @author LL
     */
    public function getClientConfig(string $name): array {
        return [
            'client_id'     => intval(config("auth." . $name . "_oauth_client_id")),
            'client_secret' => config("auth." . $name . "_oauth_client_secret"),
        ];
    }
    public function Login(string $username,string $password,array $options = []):array{
        return $this->IsPost(array_merge([
            'grant_type' => 'password',
            'username'   => $username,
            'password'   => $password,
            'scope'      => '*',
        ], $options));
    }
    private  function IsPost($param){
        try {

            $response = $this->client->post(
                $this->passportTokenUrl,
                ['form_params' => $param]);

            $data = $response->getBody()->getContents();
            $data = json_decode($data, true);
            $data['access_token'] = $data['token_type'] . " " . $data['access_token'];
           return $data;
        }catch (ClientException $exception){

            $this->clientException($exception);
        }
    }
    private function clientException($exception){
        if ($exception->getResponse()->getStatusCode() != 401 &&
            $exception->getResponse()->getStatusCode() != 400) {
            throw new ServerException();
        }
        $data = $exception->getResponse()->getBody()->getContents();
        $data = json_decode($data, true);

        switch ($data['error']) {
            case "invalid_grant":
                throw new BaseException('账号密码与客户端不匹配', -1, 401);
            case 'invalid_client':
                throw new BaseException('无效的客户端，请联系管理员', -1, 401);
            case 'invalid_request':
                throw new BaseException('刷新令牌无效', 1, 401);
        }
        throw new ServerException($exception->getMessage());
    }

}
